import os
import yaml
from pathlib import Path
from dotenv import load_dotenv
import logging
from datetime import datetime
from src import FileHandler

# 创建 logger
config_logger = logging.getLogger()

# 生成带日期的日志文件名
date_suffix = datetime.now().strftime("%Y%m%d")
log_filename = f"config_log_{date_suffix}"

# 每天生成一个新的日志文件
file_handler = FileHandler(f"config/logs/{log_filename}.log", when="midnight", interval=1, backupCount=7,
                           encoding="utf-8")
config_logger.addHandler(file_handler)


def load_config():
    # 获取当前文件的目录（即 src/config/）
    current_dir = Path(__file__).resolve().parent

    # 项目根目录为 current_dir 的上两级目录（可根据实际情况调整）
    project_root = current_dir.parent
    config_logger.debug(f"项目根目录为{project_root}")
    # 构建配置文件路径
    env_file = project_root.parent / ".env"
    if env_file.exists():
        load_dotenv(env_file)
    env = os.getenv("APP_ENV", "dev")  # 默认为 dev 环境
    config_file = project_root / f"config/config_{env}.yaml"
    config_logger.info(f"当前生效配置为{config_file}")
    if not os.path.exists(config_file):
        raise FileNotFoundError(f"找不到配置文件：{config_file}")

    with open(config_file, 'r', encoding='utf-8') as file:
        return yaml.safe_load(file)


# 获取数据库配置
config = load_config()
db_config = config['database']